
import { _decorator, Component, Node, EditBox, Label, instantiate, CameraComponent, Vec3, game } from 'cc';
import { ballcontrol } from '../demo/roll-a-ball/scripts/ball-control';
import GCmd from './config/GCmd';
import GEvent from './config/GEvent';
import NetWork from './network/NetWork';
import EventDispatch from './utils/EventDispatch';
import Utils from './utils/utils';
const { ccclass, property } = _decorator;

@ccclass('Main')
export class Main extends Component {
    @property(EditBox)
    editbox: EditBox | null = null;

    @property(Node)
    ball : Node | null = null;

    @property(Node)
    labelBall : Node | null = null;

    onLoad()
    {
        // game.setFrameRate(30);
    }

    start(){
        this.labelBall.active = false;
        this.startConnect();
        this.initEventListen();
    }

    startConnect () {
        NetWork.connectToWsserver();
    }

    initEventListen () {
        EventDispatch.instance().on(GEvent.USER_LOGIN_SUCCESS, this.onLoginSuccesEvent, this);
        EventDispatch.instance().on(GEvent.USER_LOGIN_FAIL, this.onLoginFailEvent, this);
    }

    onLoginSuccesEvent (data) {
        console.log('login success :', data.username);

        this.createBall(data.username);
    }

    createBall(username : string)
    {
        let cloneBall = instantiate(this.ball);
        cloneBall.parent = this.ball.parent;
        let control = cloneBall.getComponent(ballcontrol);
        control.username = username;
        cloneBall.active = true;

        control.labelBall = instantiate(this.labelBall);
        control.labelBall.parent = this.labelBall.parent;
        control.labelBall.getComponent(Label).string = username;
        control.labelBall.active = true;
    }

    onLoginFailEvent(data)
    {
        console.log('login fail :', data.username);
    }

    onLogin() {
        Utils.myUsername = this.editbox.string;
        console.log("username: ", Utils.myUsername);
        
        NetWork.sendDataToServer(this.node, GCmd.ClientCmd.USER_LOGIN, {username: Utils.myUsername});
    }
}
